package utils

import (
	"net/http"
	"time"

	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"github.com/labstack/echo/v4"

	"night-school-api/models"
)

// 自定义验证器
type CustomValidator struct {
	validator  *validator.Validate
	translator ut.Translator
}

func (cv *CustomValidator) Validate(i interface{}) error {
	if err := cv.validator.Struct(i); err != nil {
		// 解析并翻译错误
		errs := err.(validator.ValidationErrors)
		
		msg := ""
		for _, e := range errs {
			msg += e.Translate(cv.translator) + ";\n"
		}
		return echo.NewHTTPError(http.StatusOK, returnJSON{
			Code: 400,
			Msg: msg,
		})	
	}
	return nil
}

func NewCustomValidator() *CustomValidator {
	// 初始化 validator 和中文翻译
	validate := validator.New()

	// 添加自定义验证规则
	validate.RegisterValidation("jsontime", func(fl validator.FieldLevel) bool {
		value := fl.Field().Interface()
		// 尝试转换为 `CustomTime`
		ct, ok := value.(models.JSONTime)
		if !ok {
			// echo.New().Logger.Error("Validating time:", ct.Time)
			return false
		}
		var zeroTime time.Time
		if ct.Time.UnixNano() == zeroTime.UnixNano() {
			return false
		} else {
			return true
		}
	})

	validate.RegisterValidation("jsontime_no_seconds", func(fl validator.FieldLevel) bool {
		value := fl.Field().Interface()
		// 尝试转换为 `CustomTime`
		ct, ok := value.(models.JSONTimeNoSeconds)
		if !ok {
			// echo.New().Logger.Error("Validating time:", ct.Time)
			return false
		}
		var zeroTime time.Time
		if ct.Time.UnixNano() == zeroTime.UnixNano() {
			return false
		} else {
			return true
		}

	})


	zhT := zh.New()
	uni := ut.New(zhT, zhT)
	translator, _ := uni.GetTranslator("zh")
	_ = zh_translations.RegisterDefaultTranslations(validate, translator)

	// 设置自定义验证器
	return &CustomValidator{validator: validate, translator: translator}
}